package com.example.userdepartment.service.impl;

import com.example.userdepartment.entity.Auth;
import com.example.userdepartment.mapper.AuthMapper;
import com.example.userdepartment.security.JwtTokenUtil;
import com.example.userdepartment.service.AuthService;
import com.example.userdepartment.vo.AuthVO;
import com.example.userdepartment.vo.LoginVO;
import com.example.userdepartment.vo.RegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 认证服务实现类
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    public AuthServiceImpl(@Lazy UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    @Transactional
    public AuthVO register(RegisterVO registerVO) {
        // 检查用户名是否已存在
        if (existsByUsername(registerVO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (existsByEmail(registerVO.getEmail())) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 验证密码确认
        if (!registerVO.getPassword().equals(registerVO.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }

        // 创建新用户
        Auth auth = new Auth();
        auth.setUsername(registerVO.getUsername());
        auth.setPassword(passwordEncoder.encode(registerVO.getPassword()));
        auth.setEmail(registerVO.getEmail());
        auth.setPhone(registerVO.getPhone());
        auth.setRole("ROLE_USER");
        auth.setStatus(1);
        auth.setCreateTime(new Date());
        auth.setUpdateTime(new Date());

        // 保存用户
        authMapper.insert(auth);

        // 生成 token
        UserDetails userDetails = userDetailsService.loadUserByUsername(auth.getUsername());
        String token = jwtTokenUtil.generateToken(userDetails);

        // 返回认证信息
        AuthVO authVO = new AuthVO();
        authVO.setId(auth.getId());
        authVO.setUsername(auth.getUsername());
        authVO.setEmail(auth.getEmail());
        authVO.setRole(auth.getRole());
        authVO.setToken(token);
        authVO.setLastLoginTime(new Date());

        // 更新最后登录时间
        authMapper.updateLastLoginTime(auth.getId(), new Date());

        return authVO;
    }

    @Override
    public AuthVO login(LoginVO loginVO) {
        try {
            // 认证用户
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginVO.getUsername(), loginVO.getPassword())
            );
        } catch (DisabledException e) {
            throw new RuntimeException("用户已被禁用");
        } catch (BadCredentialsException e) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 获取用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginVO.getUsername());
        Auth auth = authMapper.findByUsername(loginVO.getUsername());

        // 生成 token
        String token = jwtTokenUtil.generateToken(userDetails);

        // 更新最后登录时间
        Date lastLoginTime = new Date();
        authMapper.updateLastLoginTime(auth.getId(), lastLoginTime);

        // 返回认证信息
        AuthVO authVO = new AuthVO();
        authVO.setId(auth.getId());
        authVO.setUsername(auth.getUsername());
        authVO.setEmail(auth.getEmail());
        authVO.setRole(auth.getRole());
        authVO.setToken(token);
        authVO.setLastLoginTime(lastLoginTime);

        return authVO;
    }

    @Override
    public Auth findByUsername(String username) {
        return authMapper.findByUsername(username);
    }

    @Override
    public boolean existsByUsername(String username) {
        return authMapper.findByUsername(username) != null;
    }

    @Override
    public boolean existsByEmail(String email) {
        return authMapper.findByEmail(email) != null;
    }
} 